<template>
  <q-page class="q-pa-md">
    <div class="q-pb-md text-h5">{{ pageTitle }} <span class="text-subtitle1">{{ pageSubTitle }}</span></div>
    <div class="q-pa-sm shadow-2 q-mb-md">
      <div class="btn q-gutter-sm">
        <q-btn @click="detailNav.goBackToList" color="primary" icon="arrow_back" outline :title="$t('返回')" no-caps />
        <q-btn @click="loadModelData" color="primary" dense icon="refresh" outline :title="$t('刷新')" no-caps :disable="loadingState"
          :loading="loadingState" v-if="isViewOrEditMode" />
        <q-btn @click="detailNav.goEditMode" color="primary" icon="edit" :label="$t('编辑')" no-caps
          v-if="fx.hasModifyRight('Comm.Exchange.Edit') && isViewMode"
          :disable="loadingState" />
        <q-btn @click="deleteExchange" color="red" icon="delete_outline" :label="$t('删除')" no-caps
          v-if="fx.hasModifyRight('Comm.Exchange.Edit') && isViewMode"
          :disable="loadingState" />
        <q-btn @click="doSubmit" color="primary" :loading="submittingState" :label="$t('确定')" no-caps
          v-if="isCreateOrEditMode" :disable="loadingState" />
        <q-btn @click="detailNav.cancelSubmit" color="primary" outline :label="$t('取消')" no-caps v-if="isEditMode"
          :disable="submittingState" />
      </div>
    </div>
    <!--错误提示-->
    <q-banner class="text-white bg-red q-my-md" dense inline-actions v-if="serverErrorMessage">
      {{ serverErrorMessage }}
      <template v-slot:action>
        <q-btn flat icon="close" size="sm" dense @click="serverErrorMessage=''" />
      </template>
    </q-banner>
    <!--折叠栏开始-->
    <!-- form -->
    <form-field-group title="主要信息" no-caps :model-with-create-update="$d.form" model-id="exchangeId">
      <div class="q-pa-sm">
        <div class="row q-col-gutter-sm q-pb-sm">
          <div class="col-12 col-sm-6 col-md-4 col-lg-3">
            <q-icon color="red" name="fas fa-asterisk" size="10px" />
            <span>{{$t('原货币')}}</span>
            <simple-filter-select :options="$d.currencyList"
              :option-label="item => item.codeName2 + '(' + item.codeName1 + ')'" option-value="codeValue"
              v-model="$d.form.fromCurrency" :search-label-and-value="true" :readonly="isViewMode"
              :error="v$.fromCurrency.$error" :error-message="e$(v$.fromCurrency.$errors)" />
          </div>
          <div class="col-12 col-sm-6 col-md-4 col-lg-3">
            <q-icon color="red" name="fas fa-asterisk" size="10px" />
            <span>{{$t('目标货币')}}</span>
            <simple-filter-select :options="$d.currencyList"
              :option-label="item => item.codeName2 + '(' + item.codeName1 + ')'" option-value="codeValue"
              v-model="$d.form.toCurrency" :search-label-and-value="true" :readonly="isViewMode"
              :error="v$.fromCurrency.$error" :error-message="e$(v$.fromCurrency.$errors)" />
          </div>
        </div>
        <div class="row q-col-gutter-sm q-pb-sm">
          <div class="col-12 col-sm-6 col-md-4 col-lg-3">
            <q-icon color="red" name="fas fa-asterisk" size="10px" />
            <span>{{$t('起始时间')}}</span>
            <q-input :error-message="e$(v$.fromDt.$errors)" :error="v$.fromDt.$error" :hide-bottom-space="true"
              clearable
              dense no-error-icon outlined square stack-label v-model="$d.form.fromDt" :readonly="isViewMode">
              <q-menu :fit="false" ref="dtp-container-1" transition-hide="none" transition-show="none"
                v-if="isCreateOrEditMode">
                <q-date :title="$d.form.fromDt" @update:model-value="() => $refs['dtp-container-1'].hide()"
                  mask="YYYY-MM-DD" :subtitle="$t('当前选中日期')" today-btn v-model="$d.form.fromDt" />
              </q-menu>
              <template v-slot:append v-if="isCreateOrEditMode">
                <q-icon name="event" />
              </template>
            </q-input>
          </div>
          <div class="col-12 col-sm-6 col-md-4 col-lg-3">
            <q-icon color="red" name="fas fa-asterisk" size="10px" />
            <span>{{$t('结束时间')}}</span>
            <q-input :error-message="e$(v$.toDt.$errors)" :error="v$.toDt.$error" :hide-bottom-space="true" clearable
              dense no-error-icon outlined square stack-label v-model="$d.form.toDt" :readonly="isViewMode">
              <q-menu :fit="false" ref="dtp-container-2" transition-hide="none" transition-show="none"
                v-if="isCreateOrEditMode">
                <q-date :title="$d.form.toDt" @update:model-value="() => $refs['dtp-container-2'].hide()"
                  mask="YYYY-MM-DD" :subtitle="$t('当前选中日期')" today-btn v-model="$d.form.toDt" />
              </q-menu>
              <template v-slot:append v-if="isCreateOrEditMode">
                <q-icon name="event" />
              </template>
            </q-input>
          </div>
        </div>
        <div class="row q-col-gutter-sm q-pb-sm">
          <div class="col-12 col-sm-6 col-md-4 col-lg-3">
            <q-icon color="red" name="fas fa-asterisk" size="10px" />
            <span>{{$t('汇率')}}</span>
            <q-input v-model="$d.form.exchangeRate" :error="v$.exchangeRate.$error"
              :error-message="e$(v$.exchangeRate.$errors)"
              :hide-bottom-space="true" :readonly="isViewMode" autofocus dense :maxlength="30" no-error-icon outlined
              square stack-label></q-input>
          </div>
          <div class="col-12 col-sm-6 col-md-4 col-lg-3">
            <q-icon color="red" name="fas fa-asterisk" size="10px" />
            <span>{{$t('有效')}}</span>
            <div class="bg-grey-3">
              <q-checkbox dense :disable="isViewMode" class="full-width q-pa-xs" color="primary"
                v-model="$d.form.isEnabled" />
            </div>
          </div>
        </div>
        <div class="row q-col-gutter-sm col-12">
          <div class="col-12">
            <span>{{$t('描述')}}</span>
            <q-input v-model="$d.form.descriptions" :hide-bottom-space="true" :readonly="isViewMode" autofocus dense
              :maxlength="30" no-error-icon outlined square stack-label></q-input>
          </div>
        </div>
      </div>
    </form-field-group>
  </q-page>
</template>

<script lang="ts">
export default {
  name: 'ExchangeStd'
}
</script>

<script lang="ts" setup>
import {useTitleHelper} from '../../hooks/titleHelper'
import {computed, reactive, ref} from 'vue'
import {ExchangeInfo} from '../../defs/exchange'
import useVuelidate from '@vuelidate/core'
import {useDetailHelper} from '../../hooks/detailHelper'
import FormFieldGroup from '../../components/FormFieldGroup.vue'
import {CodeLineForDropdown} from '../../helper/dropdownlist.d'
import { useI18n } from 'vue-i18n'
const {t} = useI18n()

const pageTitle = t('汇率管理')

useTitleHelper(pageTitle)

// 新建时候的默认值
const defFormDataForCreate = {
  isEnabled: true,
}

let serverErrorMessage = ref('')

let $d = reactive({
  // 表单数据
  form: {} as ExchangeInfo,
  currencyList: [] as CodeLineForDropdown[]
})

const validators = $f.validators

//主表单验证
const rules = {
  fromDt: {
    required: validators.required,
    date: validators.date
  },
  toDt: {
    required: validators.required,
    date: validators.date
  },
  fromCurrency: {
    required: validators.required
  },
  toCurrency: {
    required: validators.required
  },
  exchangeRate: {
    required: validators.required,
    greaterThan: validators.greaterThan(0),
    decimal: validators.decimal(6),
    betweenOpen: validators.betweenOpen(0,10000000000)
  }
}

const v$ = useVuelidate(rules, computed(() => $d.form), {$autoDirty: true})

let loadingState = ref(false)

// 加载数据
const loadModelData = function () {
  serverErrorMessage.value = ''
  loadingState.value = true
  $f.axios
    .get<ExchangeInfo>('/comm/exchange/get-exchange/' + detailInfo.itemId)
    .then((result) => {
      $d.form = result.data
      $d.form.fromDt = $f.fmt.dtFmtDateOnly($d.form.fromDt)
      $d.form.toDt = $f.fmt.dtFmtDateOnly($d.form.toDt)
      $f.misc.simpleAssign($d.form, result.data)
    })
    .catch((err) => {
      $f.ui.showNotifyFailed($f.getAxiosErrMsg(err))
    })
    .finally(() => {
      loadingState.value = false
    })
}

const {
  detailInfo,
  detailStatus,
  detailNav
} = useDetailHelper('/comm/basic/exchange',
  $d.form,
  defFormDataForCreate,
  '/comm/basic/exchange',
  '/comm/basic/exchange/detail',
  '/comm/basic/exchange/create',
  '/comm/basic/exchange/edit',
  loadModelData,
  serverErrorMessage
)

const {
  isViewMode,
  isCreateMode,
  isEditMode,
  isCreateOrEditMode,
  isViewOrEditMode,
  pageSubTitle
} = detailStatus

// 数据加载/提交状态
const submittingState = ref(false)

// 修改/新增提交
const doSubmit = function () {
  serverErrorMessage.value = ''
  void v$.value
    .$validate()
    .then((valRes) => {
      if (valRes) {
        if (isCreateMode.value) {
          submittingState.value = true
          $f.axios
            .post('/comm/exchange/create-exchange', $d.form)
            .then(() => {
              detailNav.goBackToList()
            })
            .catch((err) => {
              serverErrorMessage.value = $f.getAxiosErrMsg(err)
            })
            .finally(() => {
              submittingState.value = false
            })
        } else if (isEditMode.value) {
          submittingState.value = true
          $f.axios.post('/comm/exchange/update-exchange', $d.form)
            .then(() => {
              detailNav.doneEdit()
            })
            .catch((err) => {
              serverErrorMessage.value = $f.getAxiosErrMsg(err)
            })
            .finally(() => {
              submittingState.value = false
            })
        }
      }
    })
}

// 删除
const deleteExchange = function () {
  void $f.ui.messageBox({
    caption: t('操作确认'),
    text: t('确定要删除该汇率区间吗?'),
    icon: 'Warning',
    buttons: 'OkCancel',
    delayClose: true
  }).then((btn) => {
    if (btn === 'ok') {
      $f.axios
        .post('/comm/exchange/delete-exchange/' + detailInfo.itemId)
        .then(() => {
          $f.ui.closeMsgBox()
          detailNav.goBackToList()
        })
        .catch((err) => {
          void $f.ui.messageBox({
            caption: t('删除失败'),
            text: $f.getAxiosErrMsg(err),
            icon: $f.getAxiosErrIcon(err),
            buttons: 'Close'
          })
        })
    }
  })
}

// region 初始化
// 获取币别
void $f.lst.getCodeForDropdown('Currency').then((resp) => {
  $d.currencyList = resp
})
const fx = $f
const e$ = $f.getFieldErrStr
// endregion

</script>
